﻿using KingRoad.EPM.CompletionMaterialsBLL.UIRules;
using KingRoad.EPM.CompletionMaterialsEntity.Model;
using KingRoad.EPM.Web.Areas.CompletionMaterials.CompletionMaterialsFramework.Common;
using KingRoad.EPM.Web.Areas.CompletionMaterials.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace KingRoad.EPM.Web.Areas.CompletionMaterials.Controllers
{
    public class FileCheckController : BaseController
    {
        /// <summary>
        /// 竣工资料—案卷资料查看
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 左侧材料类型
        /// </summary>
        /// <param name="proId"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public JsonResult AsyncFileDataJson(string proId, string id)
        {
            List<treeNodes> treenodes = new List<treeNodes>();
            if (proId == null)
            {
                DotNet.Model.MyEntity.Base_Organize organInfo = GetLoginUserOrganizeEntity;
                string uname = PRJUName;
                string dname = GetLoginUserDepartmentName;

                string section = "";
                if (dname != null && uname != dname)
                    section = " and P_Section in (" + Get_JL_JC_ZDJL_SG_SegmentCodes() + ") ";
                string sql = " Pr_ID=" + PRJID + section;
                List<BcdProjectInfo> pList = BcdProjectUIRule.GetEntityListBySql(sql);
                foreach (BcdProjectInfo pInfo in pList)
                {
                    treeNodes pnode = new treeNodes();
                    pnode.proId = pInfo.P_ID;
                    pnode.pId = "null";
                    pnode.id = pInfo.P_ID + pInfo.Fd_ID;
                    pnode.open = "true";
                    pnode.name = pInfo.Fd_Numb + " " + pInfo.P_Section + pInfo.Fd_Name;
                    //文件材料（已归档）
                    int pcount2 = BcdVolumedirectoryUIRule.GetCountBySql(" P_ID='" + pInfo.P_ID + "' and (Fd_ID='" + pInfo.Fd_ID + "' or Fd_PIds like '%" + pInfo.Fd_ID + "%') and Vd_State=2 ");
                    //案卷
                    int pfcount = BcdFilelistUIRule.GetCountBySql(" P_ID='" + pInfo.P_ID + "' and (Fd_ID='" + pInfo.Fd_ID + "' or Fd_PIds like '%" + pInfo.Fd_ID + "%') ");
                    pnode.name = "(<span class='span1'>" + pcount2 + "</span>" + "/" + "<span class='span2'>" + pfcount + "</span>)" + pnode.name;

                    treenodes.Add(pnode);

                    List<BcdProjectfileInfo> pfList = BcdProjectfileUIRule.GetEntityListBySql(" P_ID='" + pInfo.P_ID + "' and Fd_PID='" + pInfo.Fd_ID + "' ");
                    foreach (BcdProjectfileInfo info in pfList)
                    {
                        treeNodes node = new treeNodes();
                        node.proId = pInfo.P_ID;
                        node.pId = pInfo.P_ID + info.Fd_PID;
                        node.id = pInfo.P_ID + info.Fd_ID;
                        node.name = info.Fd_Numb + " " + info.Fd_Name;
                        int count = BcdProjectfileUIRule.GetCountByPIDAndFdID(pInfo.P_ID, info.Fd_ID);
                        if (count > 0)
                            node.isParent = true;

                        //文件材料（已归档）
                        int count2 = BcdVolumedirectoryUIRule.GetCountBySql(" P_ID='" + pInfo.P_ID + "' and (Fd_ID='" + info.Fd_ID + "' or Fd_PIds like '%" + info.Fd_ID + "%') and Vd_State=2 ");
                        //案卷
                        int fcount = BcdFilelistUIRule.GetCountBySql(" P_ID='" + pInfo.P_ID + "' and (Fd_ID='" + info.Fd_ID + "' or Fd_PIds like '%" + info.Fd_ID + "%') ");
                        node.name = "(<span class='span1'>" + count2 + "</span>" + "/" + "<span class='span2'>" + fcount + "</span>)" + node.name;
                        treenodes.Add(node);
                    }
                }
            }
            else
            {
                id = id.Replace(proId, "");
                List<BcdProjectfileInfo> pfList = BcdProjectfileUIRule.GetEntityListBySql(" P_ID='" + proId + "' and Fd_PID='" + id + "' ");
                foreach (BcdProjectfileInfo info in pfList)
                {
                    treeNodes node = new treeNodes();
                    node.proId = proId;
                    node.pId = proId + info.Fd_PID;
                    node.id = proId + info.Fd_ID;
                    node.name = info.Fd_Numb + " " + info.Fd_Name;
                    //node.target = "ajax";
                    //node.url = "/CompletionMaterials/FileList/Detail?type=" + type + "&proId=" + proId + "&id=" + proId + info.Fd_ID;
                    int count = BcdProjectfileUIRule.GetCountByPIDAndFdID(proId, info.Fd_ID);
                    if (count > 0)
                        node.isParent = true;

                    //文件材料（已归档）
                    int count2 = BcdVolumedirectoryUIRule.GetCountBySql(" P_ID='" + proId + "' and (Fd_ID='" + info.Fd_ID + "' or Fd_PIds like '%" + info.Fd_ID + "%') and Vd_State=2 ");
                    //案卷
                    int fcount = BcdFilelistUIRule.GetCountBySql(" P_ID='" + proId + "' and (Fd_ID='" + info.Fd_ID + "' or Fd_PIds like '%" + info.Fd_ID + "%') ");
                    node.name = "(<span style='color:#dbde35'>" + count2 + "</span>" + "/" + "<span style='color:#428bca'>" + fcount + "</span>)" + node.name;
                    treenodes.Add(node);
                }
            }
            return Json(treenodes, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 右侧材料文件
        /// </summary>
        /// <param name="proId">项目id</param>
        /// <param name="id">类型id</param>
        /// <returns></returns>
        public ActionResult Detail(string tab_i, string proId, string id)
        {
            BcdFileListViewModel vm = new BcdFileListViewModel();
            ViewBag.Tab_i = tab_i;
            ViewBag.ProId = proId;
            ViewBag.FId = id;
            if (id != null && id != "null" && id != "")
            {
                id = id.Replace(proId, "");
                //项目与案卷类型详情
                BcdProjectInfo info = new BcdProjectInfo();
                if (proId != null && proId != "null")
                {
                    BcdFiledataInfo fdInfo = BcdFiledataUIRule.GetEntityById(new Guid(id));
                    if (fdInfo.Fd_PID == null || fdInfo.Fd_PID == "null")
                        info = BcdProjectUIRule.GetEntityById(new Guid(proId));
                    else
                    {
                        List<BcdProjectfileInfo> fList = BcdProjectfileUIRule.GetEntityListBySql(" P_ID='" + proId + "' and Fd_ID='" + id + "' ");
                        BcdProjectfileInfo fInfo = new BcdProjectfileInfo();
                        if (fList.Count > 0)
                        {
                            fInfo = fList[0];
                            info.P_Name = fInfo.P_Name;
                            info.P_Code = fInfo.P_Code;
                            info.Fd_ID = fInfo.Fd_ID;
                            info.Fd_Name = fInfo.Fd_Name;
                            info.Fd_UType = fInfo.Fd_UType;
                            info.P_UType = fInfo.Fd_UType;
                            info.P_Section = fInfo.P_Section;
                            info.P_Unit = fInfo.P_Unit;
                            info.Fd_Code = fInfo.Fd_Code;
                            info.Fd_Kept = fInfo.Fd_Kept;
                            info.Fd_Kit = fInfo.Fd_Kit;
                            info.Fd_Table = fInfo.Fd_Table;
                            info.Fd_Remark = fInfo.Fd_Remark;
                        }
                    }
                    if (info.Fd_Code != "")
                    {
                        if (info.Fd_UType == "项目法人" || info.Fd_UType == "相关单位")
                            info.Fd_Code = info.P_Code + info.Fd_Code.Substring(info.Fd_Code.IndexOf('/'));
                        if (info.Fd_UType == "设计单位")
                            info.Fd_Code = info.P_Code + "（设计）" + info.Fd_Code.Substring(info.Fd_Code.IndexOf('/'));
                        if (info.Fd_UType == "施工单位" || info.Fd_UType == "监理单位" || info.Fd_UType == "施工、监理")
                            info.Fd_Code = info.P_Code + "（" + info.P_Section + "）" + info.Fd_Code.Substring(info.Fd_Code.IndexOf('/'));
                    }
                }
                vm.TheBcdProjectInfo = info;
            }
            else
            {
                vm.TheBcdProjectInfo = new BcdProjectInfo();
            }
            return View(vm);
        }

        #region 文件材料
        /// <summary>
        /// 文件列表
        /// </summary>
        /// <param name="type"></param>
        /// <param name="proId"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult VolumeList(string type, string proId, string id)
        {
            BcdFileListViewModel vm = new BcdFileListViewModel();
            ViewBag.Type = type;
            //第几页
            ViewBag.pageNum = 1;
            //每页多少条
            ViewBag.numPerPage = 20;
            if (id != null && id != "null" && id != "")
            {
                id = id.Replace(proId, "");
                ViewBag.ProId = proId;
                ViewBag.FId = id;
                //案卷目录表 or Fl_ID=''
                string sql = " P_ID='" + proId + "' and (Fd_ID='" + id + "' or Fd_PIds like '%" + id + "%')  and Vd_State=2 ";
                int totalRecord = 0;
                //当前页码
                vm.TheBcdVolumedirectoryList = BcdVolumedirectoryUIRule.GetEntityListByContionRe(ViewBag.pageNum, ViewBag.numPerPage, "Vd_State,Vd_Order", out totalRecord, sql, "asc", "V_VolumeDirectory");
                vm.TheBcdVolumedirectoryList.ForEach(t =>
                {
                    t.FilePath = FilePath(t.Vd_ID, t.P_ID, t.Fd_ID);

                    t.FileCount = GetFilesCount(Server.MapPath(String.Format("~/Files/{0}", t.FilePath)), 0);
                });
                //总条数
                ViewBag.totalcount = totalRecord;
                //总页数
                ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            }
            else
            {
                vm.TheBcdFilelistList = new List<BcdFilelistInfo>();
            }
            return PartialView(vm);
        }

        public int GetFilesCount(string path, int count)
        {
            if (!System.IO.File.Exists(path))
            {
                return 0;
            }
            //如果嵌套文件夹很多，可以开子线程去统计
          count += System.IO.Directory.GetFiles(path).Length;
            foreach (var folder in System.IO.Directory.GetDirectories(path))
            {
                GetFilesCount(folder, count);
            }
            return count;
        }



        /// <summary>
        /// 文件列表分页
        /// </summary>
        /// <returns></returns>
        public ActionResult VolumeListSplitPage()
        {
            BcdFileListViewModel vm = new BcdFileListViewModel();
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);
            ViewBag.Type = Request.Form["Type"];
            ViewBag.ProId = Request.Form["ProId"];
            ViewBag.FId = Request.Form["FId"];
            if (ViewBag.pageNum == 0 || ViewBag.numPerPage == 0)
                return VolumeList(ViewBag.Type, ViewBag.ProId, ViewBag.FId);
            else
            {
                //工程项目与归档类型与案卷目录对应关系表
                string sql = " P_ID='" + ViewBag.ProId + "' and (Fd_ID='" + ViewBag.FId + "'  or Fd_PIds like '%" + ViewBag.FId + "%')  and Vd_State=2 ";
                ViewBag.iput_code = Request.Form["iput_code"];
                ViewBag.iput_name = Request.Form["iput_name"];
                if (ViewBag.iput_code != "")
                    sql += " and Vd_Code like '%" + ViewBag.iput_code + "%' ";
                if (ViewBag.iput_name != "")
                    sql += " and Vd_Name like '%" + ViewBag.iput_name + "%' ";
                //案卷目录表
                vm.TheBcdVolumedirectoryList = BcdVolumedirectoryUIRule.GetEntityListByContionRe(ViewBag.pageNum, ViewBag.numPerPage, "Vd_State,Vd_Order", out totalRecord, sql, "asc", "V_VolumeDirectory");
                vm.TheBcdVolumedirectoryList.ForEach(t =>
                {
                    t.FilePath = FilePath(t.Vd_ID, t.P_ID, t.Fd_ID);
                });
                //总条数
                ViewBag.totalcount = totalRecord;
                //总页数
                ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            }
            return View("VolumeList", vm);
        }

        /// <summary>
        /// 查看文件
        /// </summary>
        /// <returns></returns>
        public ActionResult VolumeDetail(string id)
        {
            BcdFileListViewModel vm = new BcdFileListViewModel();
            //卷内目录信息Volumedirectory
            vm.TheBcdVolumedirectoryInfo = BcdVolumedirectoryUIRule.GetEntityById(new Guid(id));
            //附件
            var commonFileList = CommonFileUIRule.GetCommonFilesByConditon(vm.TheBcdVolumedirectoryInfo.Assist_ID, "FileList_Rules");//FileList_Rules  BizType类型
            ViewBag.AssisId = vm.TheBcdVolumedirectoryInfo.Assist_ID;
            ViewBag.FileIds = string.Join(",", commonFileList.Select(t => t.FILE_FILEID));
            ViewBag.DeleteIds = string.Join(",", commonFileList.Select(t => t.FILE_ID));
            ViewBag.FilePath = FilePath(vm.TheBcdVolumedirectoryInfo.Vd_ID, vm.TheBcdVolumedirectoryInfo.P_ID, vm.TheBcdVolumedirectoryInfo.Fd_ID);
            return View(vm);
        }
        #endregion

        #region 案卷列表
        /// <summary>
        /// 档案列表
        /// </summary>
        /// <param name="proId"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult FiledataList(string proId, string id)
        {
            BcdFileListViewModel vm = new BcdFileListViewModel();
            //第几页
            ViewBag.pageNum = 1;
            //每页多少条
            ViewBag.numPerPage = 20;
            if (id != null && id != "null" && id != "")
            {
                id = id.Replace(proId, "");
                ViewBag.ProId = proId;
                ViewBag.FId = id;
                //案卷表
                string sql = " P_ID='" + proId + "' and (Fd_ID='" + id + "' or Fd_PIds like '%" + id + "%') ";
                int totalRecord = 0;
                //当前页码
                vm.TheBcdFilelistList = BcdFilelistUIRule.GetEntityListByContionRe(ViewBag.pageNum, ViewBag.numPerPage, "Fl_Numb", out totalRecord, sql, "asc", "V_FileDataList");
                //总条数
                ViewBag.totalcount = totalRecord;
                //总页数
                ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            }
            else
            {
                vm.TheBcdFilelistList = new List<BcdFilelistInfo>();
            }
            return PartialView(vm);
        }
        /// <summary>
        /// 案卷列表分页
        /// </summary>
        /// <returns></returns>
        public ActionResult FiledataListSplitPage()
        {
            BcdFileListViewModel vm = new BcdFileListViewModel();
            int totalRecord = 0;
            //当前页码
            ViewBag.pageNum = Convert.ToInt32(Request.Form["pageNum"]);
            //每页多少条
            ViewBag.numPerPage = Convert.ToInt32(Request.Form["numPerPage"]);
            ViewBag.ProId = Request.Form["ProId"];
            ViewBag.FId = Request.Form["FId"];
            if (ViewBag.pageNum == 0 || ViewBag.numPerPage == 0)
                return FiledataList(ViewBag.ProId, ViewBag.FId);
            else
            {
                //工程项目与归档类型与案卷目录对应关系表
                string sql = " P_ID='" + ViewBag.ProId + "' and (Fd_ID='" + ViewBag.FId + "' or Fd_PIds like '%" + ViewBag.FId + "%') ";
                ViewBag.iput_code = Request.Form["iput_code"];
                ViewBag.iput_numb1 = Request.Form["iput_numb1"];
                ViewBag.iput_numb2 = Request.Form["iput_numb2"];
                ViewBag.iput_name = Request.Form["iput_name"];
                if (ViewBag.iput_code != "")
                    sql += " and Fl_Code like '%" + ViewBag.iput_code + "%' ";
                if (ViewBag.iput_numb1 != "")
                {
                    if (IsNumeric(ViewBag.iput_numb1))
                        sql += " and Fl_Numb>=" + ViewBag.iput_numb1;
                }
                if (ViewBag.iput_numb2 != "")
                {
                    if (IsNumeric(ViewBag.iput_numb2))
                        sql += " and Fl_Numb<=" + ViewBag.iput_numb2;
                }
                if (ViewBag.iput_name != "")
                    sql += " and Fl_Item+Fl_FileTitle+Fl_FileName like '%" + ViewBag.iput_name + "%' ";
                //案卷目录表
                vm.TheBcdFilelistList = BcdFilelistUIRule.GetEntityListByContionRe(ViewBag.pageNum, ViewBag.numPerPage, "Fl_Numb", out totalRecord, sql, "asc", "V_FileDataList");
                //总条数
                ViewBag.totalcount = totalRecord;
                //总页数
                ViewBag.pagenumshown = totalRecord % ViewBag.numPerPage == 0 ? totalRecord / ViewBag.numPerPage : totalRecord / ViewBag.numPerPage + 1;
            }
            return View("FiledataList", vm);
        }

        /// <summary>  
        /// 判断是否是数字  
        /// </summary>  
        /// <param name="str">字符串</param>  
        /// <returns>bool</returns>  
        public bool IsNumeric(string str)
        {
            if (str == null || str.Length == 0)
                return false;
            System.Text.ASCIIEncoding ascii = new System.Text.ASCIIEncoding();
            byte[] bytestr = ascii.GetBytes(str);
            foreach (byte c in bytestr)
            {
                if (c < 48 || c > 57)
                {
                    return false;
                }
            }
            return true;
        }

        /// <summary>
        /// 查看案卷信息
        /// </summary>
        /// <returns></returns>
        public ActionResult FileDetail(string id)
        {
            BcdFileListViewModel vm = new BcdFileListViewModel();
            vm.TheBcdFilelistInfo = BcdFilelistUIRule.GetEntityById(new Guid(id));
            vm.TheBcdVolumedirectoryList = BcdVolumedirectoryUIRule.GetEntityListBySql(" Fl_ID='" + id + "' ");
            vm.TheBcdVolumedirectoryList.ForEach(t =>
            {
                t.FilePath = FilePath(t.Vd_ID, t.P_ID, t.Fd_ID);
            });
            return View(vm);
        }
        public string FilePath(string vdid, string pid, string fdid)
        {
            string path = "";
            //项目信息
            BcdProjectInfo pInfo = BcdProjectUIRule.GetEntityById(new Guid(pid));
            BcdFiledataInfo fInfo = BcdFiledataUIRule.GetEntityById(new Guid(fdid));
            path = pInfo.P_Name + "/" + pInfo.P_Section;
            string pids = fdid;
            if (fInfo.Fd_PIds != null)
                pids = fInfo.Fd_PIds.Replace("'", "").Trim(',') + (fInfo.Fd_PIds == "" ? "" : ",") + fdid;
            foreach (string id in pids.Split(','))
            {
                BcdFiledataInfo info = BcdFiledataUIRule.GetEntityById(new Guid(id));
                path += info.Fd_Name + "/";
            }
            return path + vdid;
        }
        #region 导出
        /// <summary>
        /// 导出案卷
        /// </summary>
        /// <returns></returns>
        public FileResult ExportFile(string id)
        {
            string fileName = "案卷.docx";
            BcdFilelistInfo info = BcdFilelistUIRule.GetEntityById(new Guid(id));
            info.Fl_Item = info.Fl_Item + info.Fl_FileTitle + info.Fl_FileName;
            List<BcdVolumedirectoryInfo> list = BcdVolumedirectoryUIRule.GetEntityListBySql(" Fl_ID='" + id + "' ");
            var ret = base.ExportFileToWord(fileName, info, list);
            return ret;
        }

        /// <summary>
        /// 导出案卷目录
        /// </summary>
        /// <returns></returns>
        public FileResult ExportList(string proId, string fId, string code, string numb1, string numb2, string name)
        {
            //工程项目与归档类型与案卷目录对应关系表
            string sql = " P_ID='" + proId + "' and (Fd_ID='" + fId + "' or Fd_PIds like '%" + fId + "%') ";
            if (code != "")
                sql += " and Fl_Code like '%" + code + "%' ";
            if (numb1 != "")
            {
                if (IsNumeric(numb1))
                    sql += " and Fl_Numb>=" + numb1;
            }
            if (numb2 != "")
            {
                if (IsNumeric(numb2))
                    sql += " and Fl_Numb<=" + numb2;
            }
            if (name != "")
                sql += " and Fl_Item+Fl_FileTitle+Fl_FileName like '%" + name + "%' ";
            List<BcdFilelistInfo> list = BcdFilelistUIRule.GetEntityListBySql(sql);
            string fileName = "案卷目录.docx";
            int i = 0;
            foreach (BcdFilelistInfo info in list)
            {
                i++;
                info.index = i.ToString();
                info.Fl_Code = info.Fl_Code + info.Fl_Numb.ToString("D3");
                info.Fl_FileName = info.Fl_Item + info.Fl_FileTitle + info.Fl_FileName;
            }
            return base.ExportToWord(fileName, list);
        }
        #endregion
        #endregion
    }
}
